package org.jing.ext.media.m3u8.tag;

import org.jing.core.lang.ExceptionHandler;
import org.jing.core.lang.data.Carrier;
import org.jing.core.util.StringUtil;
import org.jing.ext.media.m3u8.BaseM3U8Tag;
import org.jing.ext.media.m3u8.M3U8TagType;
import org.jing.ext.media.m3u8.M3U8TagTypeInfo;

import java.util.Arrays;

/**
 * Description: <br>
 *
 * @author bksmate <br>
 * @since 2024-12-24 <br>
 */
@M3U8TagTypeInfo(M3U8TagType.EXT_X_KEY)
public class M3U8Key extends BaseM3U8Tag {
    private String method;

    private String keyPath;

    private String ivStr;

    private byte[] key;

    private byte[] iv;

    @Override public void setParameter(String value) {
        Carrier carrier = new Carrier();
        Arrays.stream(value.split(",")).forEach(p$ -> {
            String[] p = p$.trim().split("=", 2);
            carrier.setString(StringUtil.getStringFromArray(p, 0, "").trim().toUpperCase(), StringUtil.getStringFromArray(p, 1, "0").trim());
        });
        setMethod(carrier.getString("METHOD"));
        setKeyPath(carrier.getString("URI"));
        setIvStr(carrier.getString("IV"));
    }

    @Override protected String outputValue() {
        return "METHOD=" + method + ",URI=\"" + keyPath + "\",IV=" + ivStr;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        ExceptionHandler.publishIfMatch(!method.toUpperCase().contains("AES"), "key method [{}] doesnt' support", method);
        this.method = method;
    }

    public byte[] getKey() {
        return key;
    }

    public void setKey(byte[] key) {
        this.key = key;
    }

    public String getKeyPath() {
        return keyPath;
    }

    public void setKeyPath(String keyPath) {
        this.keyPath = keyPath.replace("\"", "");
    }

    public String getIvStr() {
        return ivStr;
    }

    public void setIvStr(String ivStr) {
        this.ivStr = ivStr;
    }

    public byte[] getIv() {
        return iv;
    }

    public void setIv(byte[] iv) {
        this.iv = iv;
    }
}
